import {ElMessage, ElMessageBox} from 'element-plus'
import { ref, reactive, inject, defineExpose, getCurrentInstance, ComponentInternalInstance } from 'vue';
export function useAddEdit(obj:any){
  const { proxy } : any = getCurrentInstance() as ComponentInternalInstance;
  let {api, initForm} = obj;
  let isShow = ref(false);
  let btnLoading = ref(false);
  let handle = reactive({
    type: 'add',
    name: '新增',
    methods: 'post',
  });
  let info = reactive({});
  const optionData:any = inject('optionData');
  let paramsForm:any = {};
  for(let key in initForm){
    paramsForm[key] = initForm[key];
  }
  let form = reactive(paramsForm);
  const defaultForm = JSON.parse(JSON.stringify(initForm));
  const init = (type:string, row:any) => {
    handle.type = type;
    if(type == 'add'){
      handle.name = '新增';
      handle.methods = 'post';
    }else{
      handle.name = '编辑';
      handle.methods = 'put';
      info = row;
    }
    if(row){
      proxy.$util.resetForm(form, row);
    }
    isShow.value = true;
  }
  const returnInfo = () => {
    return info;
  };
  const handleClose = () => {
    proxy.$util.resetForm(form, defaultForm);
  };
  const submitForm = (opt:any = {}) => {
    btnLoading.value = true;
    let params = Object.assign({},form, opt);
    return new Promise((resolve, reject) => {
      proxy.$request(handle.methods, api, params, (data:any,msg:any) => {
        btnLoading.value = false;
        isShow.value = false;
        ElMessage.success(msg);
        resolve(data);
      },(msg:any) => {
        btnLoading.value = false;
        reject(msg);
      });  
    })   
  };
  return{
    isShow,
    btnLoading,
    handle,
    optionData,
    form,
    init,
    returnInfo,
    handleClose,
    submitForm,

  }
}
